Prototypal Inheritance 01
- Javascript uses prototypal inheritance (Java, Python like language use classical inheritance).
- Inheritance means, an object getting access of another object methods and properties.
- It helps
- Avoid repeating functionalities
- Making innovative programming paradigms
- In Javascript,
classkeyword is asyntactic sugar. Internally it uses theprototypal inheritance. - Both
arrayandfunctionare objects in Javascript. - So any
object,arrayandfunctioncan use the property of the parent prototyped chainobjectproperties and methods.
Example 01: Array Prototype Chain
const array = [];
Here we created an array. This array object is created by the constructor of a object. We can access theses constructor anr other array methods like concat, fill, find, push, pop etc using the following,
console.log(array.__proto__);
Using prototype chain we can access the base object, using the following,
console.log(array.__proto__.__proto__);
From this base object, we can access the base object properties and methods like, constructor, hasOwnProperty, toString, valueOf etc.
Now we can use the base object method using the prototype chain. For example to use the toString method from base object, we can write
array.toString();
Since our array is empty, it will return empty string.
Example 02: Function Prototype Chain
Let's create a method
function a() {}
Using prototype chain, we can observe the native function. The native function is the one, created all other functions.
console.log(a.__proto__);
Using the prototype chain, if we go one step closer, we will find the base object.
console.log(a.__proto__.__proto__);
Example 02: Object Prototype Chain
Now let's declare a object
const obj = {};
If we check the prototype chain, we will found the base object.
console.log(obj.__proto__);